package com.milkshopbackend.milkshop.controller;

import com.milkshopbackend.milkshop.Service.AddressService;
import com.milkshopbackend.milkshop.common.Result;
import com.milkshopbackend.milkshop.entity.Address;
import com.milkshopbackend.milkshop.entity.AddressDTO;
import com.milkshopbackend.milkshop.util.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    // 获取当前用户所有收货地址
    @GetMapping
    public Result<List<Address>> list() {
        Long userId = SecurityUtils.getCurrentUserId();
        return Result.success(addressService.getUserAddresses(userId));
    }

    // 新增地址
    @PostMapping
    public Result<?> add(@Validated @RequestBody AddressDTO dto) {
        Long userId = SecurityUtils.getCurrentUserId();
        Address address = new Address();
        BeanUtils.copyProperties(dto, address);
        address.setUserId(userId);
        addressService.save(address);
        return Result.success();
    }

    // 修改地址
    @PutMapping("/{id}")
    public Result<?> update(@PathVariable Long id, @Validated @RequestBody AddressDTO dto) {
        Long userId = SecurityUtils.getCurrentUserId();
        Address address = new Address();
        BeanUtils.copyProperties(dto, address);
        address.setId(id);
        address.setUserId(userId);
        addressService.updateById(address);
        return Result.success();
    }

    // 删除地址
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        addressService.removeById(id);
        return Result.success();
    }

    // 设置默认地址
    @PutMapping("/{id}/default")
    public Result<?> setDefault(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();
        addressService.setDefaultAddress(userId, id);
        return Result.success();
    }
} 